package com.beijiteshop.shop.wxapi

import android.content.Context
import android.content.Intent
import com.beijiteshop.shop.app.WX_APP_ID
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory

/**
 * @Author LiaoZhongKai
 * @Date 2021/3/24 17:57
 * @Description
 */
class WXHelper private constructor(){

    companion object{

        const val TYPE_LOGIN = "type_login"
        const val TYPE_AUTH = "type_auth"

        private var singleton: WXHelper? = null
        get() {
            if (field == null){
                field = WXHelper()
            }
            return field
        }

        @Synchronized
        fun getInstance(): WXHelper{
            return singleton!!
        }
    }

    private var mIWXApi: IWXAPI? = null

    fun register(context: Context){
        mIWXApi = WXAPIFactory.createWXAPI(context, WX_APP_ID,true)
        mIWXApi!!.registerApp(WX_APP_ID)
    }

    fun handleIntent(intent: Intent,iwxapiEventHandler: IWXAPIEventHandler){
        mIWXApi?.handleIntent(intent,iwxapiEventHandler)
    }

    fun isWXInstalled(): Boolean{
        return mIWXApi?.isWXAppInstalled?:false
    }

    /**
     * 微信登录
     */
    fun login(){
        val sendAuth = SendAuth.Req().apply {
            scope = "snsapi_userinfo"
            state = TYPE_LOGIN
        }
        mIWXApi?.sendReq(sendAuth)
    }

    /**
     * 获取授权
     */
    fun getAuth(){
        val sendAuth = SendAuth.Req().apply {
            scope = "snsapi_userinfo"
            state = TYPE_AUTH
        }
        mIWXApi?.sendReq(sendAuth)
    }
}